﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.Win32;
using QBWeb.Models;
using QBWeb.Models.CurriculumFolder;
using QBWeb.Models.QuestionFolder;

namespace QBWeb.Controllers
{
    public class WordImportController : Controller
    {
        private readonly QBDbContext db = new QBDbContext();
       
        // GET: WordImport
        public ActionResult Index()
        {
            
            return View(db.QuestionTbs.ToList());
        }

        public ActionResult Upload()
        {
            var wordFile = Request.Files["wordFile"];
            if (wordFile == null)
            {
                ViewBag.text = "未上传文件";
                return PartialView("_LeftIndex");
            }
            string[] strArray = {"doc","docx"};
            var x = wordFile.FileName.Split('.').Last().ToLower();
            if (!strArray.Contains(x))
            {
                ViewBag.text = "不符合文件要求";
                return PartialView("_LeftIndex"); //判断文件扩展名是否符合要求
            }
            var user = User.Identity.GetUserName();
            if (user == "") user = "temp"; 
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WordFiles/") + user;
            var savePath = path+"/" + wordFile.FileName; //拼接虚拟路径
            if(!Directory.Exists(path)) 
                Directory.CreateDirectory(path);

            wordFile.SaveAs(savePath); //暂存本地
            var temp = new WordTools();
            ViewBag.text = temp.GetText(savePath);

            return PartialView("_LeftIndex");
        }


        public ActionResult Recognition(string textData)
        {
            var cacheKey = User.Identity.GetUserId() ?? "temp";  //temp 为未登陆测试用
            var getSeg = new GetSeg();
            ViewBag.text2 = getSeg.CutText(textData);
            var dicDic = (Dictionary<int, Dictionary<string, string>>) HttpContext.Cache[cacheKey];
            
            if (dicDic == null)
            {
                //缓存识别结果
                //第一个参数是键，第二个是值，第四个参数是时间，其他参数可直接为空
                HttpContext.Cache.Insert(cacheKey, ViewBag.text2, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero);
                
            }
            else
            {
                HttpContext.Cache.Insert(cacheKey, ViewBag.text2, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero);
            }
            return PartialView("_RightIndex");
        }

        public ActionResult ResultToView()
        {
            var cacheKey = User.Identity.GetUserId() ?? "temp";
            var dicDic = (Dictionary<int, Dictionary<string, string>>)HttpContext.Cache[cacheKey];
            SetSqlTools tools = new SetSqlTools();
            var res=tools.GetWordQuestionByCache(dicDic);


            return Json(res, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SaveResult()
        {
            var cacheKey = User.Identity.GetUserId() ?? "temp";
            var dicDic = (Dictionary<int, Dictionary<string, string>>)HttpContext.Cache[cacheKey];


            var userId = User.Identity.GetUserId();

            if (userId == "") userId = "Temp"; //临时key
            var cid =Convert.ToInt32(Session[userId]);
            var smallKeywords = db.SmallKnowModuleTbs.Where(a => a.CurriculumId == cid).ToList();
            foreach (var keyValuePair in dicDic)
            {
                var smallId = keyValuePair.Value["keyWords"] == "" ? null : Classification(smallKeywords,keyValuePair.Value["keyWords"]);
                
                var questionTb = new QuestionTb()
                {
                    QuestName = keyValuePair.Value["quest"],
                    SmallKnowModuleTbId=smallId,
                    QuestLevel=3,
                    CreateTime=DateTime.Now,
                    Keywords = keyValuePair.Value["keyWords"],
                    TeacherId = User.Identity.GetUserId()
                };
                
               var i= keyValuePair.Value["type"];
               switch (i)
               {
                    case "2":
                        var correctValue = keyValuePair.Value["correct"] == "对" ? 1 : 0;
                        var trueFalseTb = new TrueFalseTb()
                        {
                            QuestTypeTbId=2,  //固定位置的字段
                            CorrectValue=correctValue
                        };
                        questionTb.QuestTypeTbId = 2; //赋值固定的类型，这里类型主要用于以后组卷用
                        db.QuestionTbs.Add(questionTb);
                        db.SaveChanges();
                        trueFalseTb.QuestionTbId = questionTb.Id;
                        db.TrueFalseTbs.Add(trueFalseTb);
                        break;
                    case "1":
                        questionTb.QuestAnalysis = keyValuePair.Value["analysis"];
                        questionTb.QuestTypeTbId = 1;
                        db.QuestionTbs.Add(questionTb);
                        db.SaveChanges();
                        var alphabet = 'A';
                        for (var k=1;k<= keyValuePair.Value.Count-6;k++ )
                        {
                            var singleChoiceTb = new SingleChoiceTb
                            {
                                CorrectOption = keyValuePair.Value["correct"],
                                QuestTypeTbId = 1,
                                QuestionTbId = questionTb.Id,
                                Options =alphabet+"" ,
                                Value = keyValuePair.Value["option" + k]
                            };
                            db.SingleChoiceTbs.Add(singleChoiceTb);
                            alphabet = Convert.ToChar(alphabet + 1);
                        }
                        break;
                    case "3":
                        
                        var blanksTb = new BlanksTb
                        {
                            QuestTypeTbId=3
                           ,CorrectValue=keyValuePair.Value["blanks"]
                        };
                        questionTb.QuestTypeTbId = 3;
                        db.QuestionTbs.Add(questionTb);
                        db.SaveChanges();
                        blanksTb.QuestionTbId = questionTb.Id;
                        db.BlanksTbs.Add(blanksTb);
                        break;
               }
            }
            db?.SaveChanges();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// 简易分类
        /// </summary>
        /// <param name="smallKeywords"></param>
        /// <param name="questKeywords"></param>
        /// <returns></returns>
        public int? Classification(List<SmallKnowModuleTb> smallKeywords,string questKeywords)
        {
            if (!smallKeywords.Any()) return null; 
            var quest = questKeywords.Split(',');//对关键词进行划分
            var i = 0.0; //初始化分子
            var countQuest = quest.Count();  //分母，关键词数量
            var dicRes = new Dictionary<int, double>();//保存知识模块对应的概率
            foreach (var x in smallKeywords) //循环遍历出每个知识模块的关键词
            {
                var sk = x.Keywords.Split('\n');//划分
                foreach (var s in quest) //循环遍历出题目的每个关键词
                {
                    if (sk.Contains(s)) 
                    {
                        //可以替换复杂的近义词算法
                        i++;
                    }
                   
                }
                dicRes[x.Id] = i / countQuest;
                i = 0.0;//重置
            }
            var smallId=dicRes.OrderByDescending(a=>a.Value).First();
            if (smallId.Value == 0.0)
            {
                return null;
            }
            return smallId.Key;
        }






        //// GET: WordImport/Details/5
        //public ActionResult Details(int id)
        //{
        //    return View();
        //}

        //// GET: WordImport/Create
        //public ActionResult Create()
        //{
        //    return View();
        //}

        //// POST: WordImport/Create
        //[HttpPost]
        //public ActionResult Create(FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add insert logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}

        //// GET: WordImport/Edit/5
        //public ActionResult Edit(int id)
        //{
        //    return View();
        //}

        //// POST: WordImport/Edit/5
        //[HttpPost]
        //public ActionResult Edit(int id, FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add update logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}

        //// GET: WordImport/Delete/5
        //public ActionResult Delete(int id)
        //{
        //    return View();
        //}

        //// POST: WordImport/Delete/5
        //[HttpPost]
        //public ActionResult Delete(int id, FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add delete logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}
    }
}
